package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"react-blog-server/app/dao/model"
	"react-blog-server/app/service"
	"react-blog-server/common/auth"
	"react-blog-server/common/response"
)

func NewAuthHttp(group *gin.RouterGroup) {
	group.POST("/auth/login", Login)
	group.GET("/auth/logout", Logout)
	group.POST("/auth/register", Register)
}

func Login(c *gin.Context) {
	user := new(model.User)
	if err := c.BindJSON(user); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	user, err := service.UserService.Auth(user)
	if err != nil {
		response.Fail(c, http.StatusUnauthorized, err.Error())
		return
	}
	userInfo := &auth.UserInfo{
		Id:       user.ID,
		UserName: user.UserName,
		Email:    user.Email,
		Phone:    user.Phone,
		RealName: user.RealName,
		RoleCode: user.RoleCode,
	}
	token, err := auth.GenerateToken(userInfo)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	userInfo.Token = &token
	response.Success(c, userInfo)
}

func Logout(c *gin.Context) {
	response.Ok(c)
}

func Register(c *gin.Context) {
	user := new(model.User)
	if err := c.BindJSON(user); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	if err := service.UserService.Validate(user); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	if u, _ := service.UserService.GetUserByName(user.UserName); u != nil {
		response.Fail(c, http.StatusBadRequest, "该用户已存在")
		return
	}
	err := service.UserService.Create(user)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	user.Password = ""
	response.Success(c, user)
}
